// Game data
const gameData = {
    scenes: {
        entrance: {
            title: "入口石室",
            description: "你在一间布满象形文字的石室醒来，月光从头顶的裂缝透入。正中央的黄金石棺闪着微光，墙壁上残留着【↑→♀△】的神秘符号。左手边有具木乃伊，右手边壁画描绘着太阳船穿过十二道冥门。",
            puzzleType: "puzzle",
            puzzleText: "石棺上有四个符号槽，需要按正确顺序排列",
            solution: ["♀", "△", "↑", "→"],
            feedback: {
                success: "石棺移开露出地道！获得【青铜钥匙】",
                fail: "地面震动！木乃伊的手指动了..."
            },
            nextScene: "corridor",
            item: "青铜钥匙",
            image: "assets/1.png"
        },
        corridor: {
            title: "潮湿地道",
            description: "潮湿的地道墙壁渗出红色液体，前方传来齿轮转动声。三个石门分别刻着：①阿努比斯天平 ②荷鲁斯之眼 ③圣甲虫图腾",
            puzzleType: "riddle",
            puzzleText: "当真实重于羽毛时，哪道门通向生路？",
            answer: "②",
            hints: [
                "审判之秤与心脏重量的关系", 
                "荷鲁斯失去的眼睛象征牺牲与重生"
            ],
            feedback: {
                success: "荷鲁斯之眼石门缓缓开启，通向更深处的殿堂！",
                fail: "选择错误的门导致地面陷落，你掉入流沙陷阱！"
            },
            nextScene: "guardian_hall",
            image: "assets/2.png"
        },
        guardian_hall: {
            title: "守护者大厅",
            description: "巨大的阿米特兽雕像矗立中央，四盏油灯组成星座图案。角落的莎草纸残片写着：『四灯灭三时，真相显现』",
            puzzleType: "mechanism",
            puzzleText: "四盏油灯分别代表着不同的星座，需要按照提示熄灭正确的三盏",
            options: ["金牛座", "天蝎座", "狮子座", "双鱼座"],
            solution: ["金牛座", "天蝎座", "狮子座"],
            feedback: {
                success: "雕像底座升起，露出镶嵌红宝石的权杖！获得【红宝石权杖】",
                fail: "雕像发出低沉的咆哮，地面开始颤抖..."
            },
            nextScene: "final_chamber",
            item: "红宝石权杖",
            image: "assets/3.png"
        },
        final_chamber: {
            title: "最终密室",
            description: "法老金面具悬浮在祭坛上方，四面墙投射出星座光影。突然响起低沉的声音：『唯有平衡日月之力者，可得自由』",
            puzzleType: "final_puzzle",
            puzzleText: "需要使用收集到的物品完成最终仪式",
            requiredItems: ["青铜钥匙", "红宝石权杖"],
            solution: "将红宝石权杖插入祭坛",
            feedback: {
                success: "金字塔顶打开，晨曦中你看到现代城市的天际线。恭喜你，成功逃出法老王的诅咒！",
                fail: "能量不平衡导致祭坛崩塌，你被困在了时空裂缝中..."
            },
            ending: true,
            image: "assets/4.jpeg"
        }
    }
};

// Game state
const gameState = {
    currentScene: "entrance",
    inventory: [],
    hintsRemaining: 2,
    puzzleState: {
        selectedSymbols: [],
        selectedLamps: []
    }
};

// DOM Elements
const sceneTitle = document.getElementById("scene-title");
const sceneDescription = document.getElementById("scene-description");
const puzzleContainer = document.getElementById("puzzle-container");
const riddleContainer = document.getElementById("riddle-container");
const mechanismContainer = document.getElementById("mechanism-container");
const finalPuzzleContainer = document.getElementById("final-puzzle-container");
const puzzleText = document.getElementById("puzzle-text");
const riddleText = document.getElementById("riddle-text");
const mechanismText = document.getElementById("mechanism-text");
const finalPuzzleText = document.getElementById("final-puzzle-text");
const feedbackMessage = document.getElementById("feedback-message");
const currentSceneEl = document.getElementById("current-scene");
const inventory = document.getElementById("inventory");
const puzzleInput = document.getElementById("puzzle-input");
const puzzleSolution = document.getElementById("puzzle-solution");
const submitPuzzle = document.getElementById("submit-puzzle");
const resetPuzzle = document.getElementById("reset-puzzle");
const getHint = document.getElementById("get-hint");
const hintText = document.getElementById("hint-text");
const hintsRemaining = document.getElementById("hints-remaining");
const currentYearEl = document.getElementById("current-year");

// Update footer with current year
currentYearEl.textContent = new Date().getFullYear();

// Initialize game
function initGame() {
    // 显示加载页面
    const loadingScreen = document.getElementById("loading-screen");
    const gameContainer = document.getElementById("game-container");
    const loadingBar = document.getElementById("loading-bar");
    const loadingText = document.getElementById("loading-text");

    // 模拟资源加载进度
    let progress = 0;
    const loadingInterval = setInterval(() => {
        progress += Math.random() * 15;
        if (progress > 100) progress = 100;
        loadingBar.style.width = `${progress}%`;
        loadingText.textContent = `正在加载游戏资源...${Math.floor(progress)}%`;

        if (progress === 100) {
            clearInterval(loadingInterval);
            setTimeout(() => {
                loadingScreen.style.opacity = "0";
                gameContainer.style.display = "flex";
                gameContainer.style.opacity = "1";
                setTimeout(() => {
                    loadingScreen.style.display = "none";
                }, 1000);
            }, 500);
        }
    }, 100);

    // 更新版权年份
    const currentYearEl = document.getElementById("current-year");
    if (currentYearEl) {
        currentYearEl.textContent = new Date().getFullYear();
    }
    
    // 初始化游戏状态
    gameState.currentScene = "entrance";
    gameState.inventory = [];
    gameState.hintsRemaining = 2;
    gameState.puzzleState = {
        selectedSymbols: [],
        selectedLamps: []
    };
    
    // 加载初始场景
    loadScene(gameState.currentScene);
}

// Load scene
function loadScene(sceneName) {
    const scene = gameData.scenes[sceneName];
    gameState.currentScene = sceneName;
    
    // Update scene title and description
    sceneTitle.textContent = scene.title;
    sceneDescription.textContent = scene.description;
    currentSceneEl.innerHTML = `<span class="text-gray-400">当前场景：</span>${scene.title}`;
    
    // 更新场景图片
    const sceneImage = document.getElementById("scene-image");
    if (scene.image && sceneImage) {
        sceneImage.innerHTML = `
            <img src="${scene.image}" alt="${scene.title}" class="w-full h-full object-cover">
            <div class="scene-title-overlay">${scene.title}</div>
        `;
    } else {
        // 默认图片占位符
        sceneImage.innerHTML = `
            <i class="fas fa-pyramid text-6xl text-amber-500 opacity-50"></i>
            <p class="absolute text-xs text-gray-400 bottom-2 right-2">图片占位符</p>
        `;
    }
    
    // 完全清除交互元素区域，彻底移除前一个关卡的内容
    const interactiveElements = document.getElementById("interactive-elements");
    interactiveElements.innerHTML = '';
    
    // 隐藏反馈信息
    feedbackMessage.classList.add("hidden");
    
    // 重置提示系统
    gameState.hintsRemaining = 2;
    
    // 显示场景切换提示
    showSceneTransitionMessage(scene.title);
    
    // 根据关卡类型创建对应的交互界面
    if (scene.puzzleType === "puzzle") {
        // 第一关：符号排序谜题
        interactiveElements.innerHTML = `
            <div id="puzzle-container" class="bg-slate-700 p-3 rounded-md">
                <p class="text-amber-300 mb-2"><i class="fas fa-puzzle-piece mr-1"></i> <span id="puzzle-text">${scene.puzzleText}</span></p>
                
                <div id="puzzle-input" class="flex gap-2 mb-4 justify-center">
                    <button class="puzzle-btn w-10 h-10 bg-slate-600 rounded-md flex items-center justify-center text-xl" data-symbol="♀">♀</button>
                    <button class="puzzle-btn w-10 h-10 bg-slate-600 rounded-md flex items-center justify-center text-xl" data-symbol="△">△</button>
                    <button class="puzzle-btn w-10 h-10 bg-slate-600 rounded-md flex items-center justify-center text-xl" data-symbol="↑">↑</button>
                    <button class="puzzle-btn w-10 h-10 bg-slate-600 rounded-md flex items-center justify-center text-xl" data-symbol="→">→</button>
                </div>
                
                <div id="puzzle-solution" class="flex gap-2 justify-center mb-4">
                    <div class="solution-slot w-10 h-10 border-2 border-amber-500 rounded-md flex items-center justify-center text-xl"></div>
                    <div class="solution-slot w-10 h-10 border-2 border-amber-500 rounded-md flex items-center justify-center text-xl"></div>
                    <div class="solution-slot w-10 h-10 border-2 border-amber-500 rounded-md flex items-center justify-center text-xl"></div>
                    <div class="solution-slot w-10 h-10 border-2 border-amber-500 rounded-md flex items-center justify-center text-xl"></div>
                </div>
                
                <div class="flex justify-center">
                    <button id="submit-puzzle" class="btn-egypt px-4 py-2 rounded-md font-bold">解开石棺</button>
                    <button id="reset-puzzle" class="ml-2 px-4 py-2 bg-slate-600 rounded-md hover:bg-slate-500">重置</button>
                </div>
                
                <p class="text-amber-100 text-sm mt-3 italic"><i class="fas fa-info-circle mr-1"></i> 提示：点击上方的符号，将它们放入下方的空格中，尝试找出正确的顺序。</p>
            </div>
        `;
        
        // 重置并绑定谜题事件
        resetPuzzleState();
        setupPuzzleEvents();
        
    } else if (scene.puzzleType === "riddle") {
        // 第二关：谜语选择题
        interactiveElements.innerHTML = `
            <div id="riddle-container" class="bg-slate-700 p-3 rounded-md">
                <p class="text-amber-300 mb-2"><i class="fas fa-question-circle mr-1"></i> <span id="riddle-text">${scene.puzzleText}</span></p>
                
                <div id="riddle-options" class="flex flex-col sm:flex-row gap-4 justify-center mb-4">
                    <button class="riddle-option px-4 py-2 bg-slate-600 rounded-md hover:bg-slate-500" data-option="①">①阿努比斯天平</button>
                    <button class="riddle-option px-4 py-2 bg-slate-600 rounded-md hover:bg-slate-500" data-option="②">②荷鲁斯之眼</button>
                    <button class="riddle-option px-4 py-2 bg-slate-600 rounded-md hover:bg-slate-500" data-option="③">③圣甲虫图腾</button>
                </div>
                
                <div id="hint-system" class="text-center">
                    <p id="hint-text" class="text-gray-300 italic mb-2 hidden"></p>
                    <button id="get-hint" class="text-amber-400 hover:text-amber-300"><i class="fas fa-lightbulb mr-1"></i>获取提示 (<span id="hints-remaining">2</span>次)</button>
                </div>
                
                <p class="text-amber-100 text-sm mt-3 italic"><i class="fas fa-info-circle mr-1"></i> 提示：古埃及的冥界审判中，心脏与羽毛的重量有特殊意义。</p>
            </div>
        `;
        
        // 更新提示次数显示
        const hintsRemaining = document.getElementById("hints-remaining");
        if (hintsRemaining) hintsRemaining.textContent = gameState.hintsRemaining;
        
        // 绑定谜语选择事件
        setupRiddleEvents();
        
    } else if (scene.puzzleType === "mechanism") {
        // 第三关：机关谜题
        createMechanismInterface(scene);
    } else if (scene.puzzleType === "final_puzzle") {
        // 第四关：最终谜题
        createFinalPuzzleInterface(scene);
    }
}

// 显示场景切换信息
function showSceneTransitionMessage(sceneTitle) {
    // 创建场景切换通知
    const transitionMessage = document.createElement('div');
    transitionMessage.className = 'fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-black bg-opacity-80 text-amber-300 px-8 py-6 rounded-lg text-center z-50 transition-opacity duration-1000';
    transitionMessage.style.opacity = '0';
    transitionMessage.innerHTML = `
        <h3 class="text-xl font-bold mb-2">进入 ${sceneTitle}</h3>
        <p class="text-sm text-amber-200">新的挑战在等待着你...</p>
    `;
    document.body.appendChild(transitionMessage);
    
    // 动画显示然后淡出
    setTimeout(() => {
        transitionMessage.style.opacity = '1';
        setTimeout(() => {
            transitionMessage.style.opacity = '0';
            setTimeout(() => transitionMessage.remove(), 1000);
        }, 1500);
    }, 100);
}

// 设置第一关符号谜题的事件监听
function setupPuzzleEvents() {
    // 符号按钮点击事件
    const puzzleBtns = document.querySelectorAll(".puzzle-btn");
    puzzleBtns.forEach(btn => {
        btn.addEventListener("click", function() {
            const symbol = this.getAttribute("data-symbol");
            if (gameState.puzzleState.selectedSymbols.length < 4) {
                gameState.puzzleState.selectedSymbols.push(symbol);
                updatePuzzleDisplay();
            }
        });
    });
    
    // 重置按钮事件
    const resetPuzzle = document.getElementById("reset-puzzle");
    if (resetPuzzle) {
        resetPuzzle.addEventListener("click", resetPuzzleState);
    }
    
    // 提交按钮事件
    const submitPuzzle = document.getElementById("submit-puzzle");
    if (submitPuzzle) {
        submitPuzzle.addEventListener("click", checkPuzzleSolution);
    }
}

// 设置第二关谜语的事件监听
function setupRiddleEvents() {
    // 谜语选项事件
    const riddleOptions = document.querySelectorAll(".riddle-option");
    riddleOptions.forEach(option => {
        option.addEventListener("click", function() {
            const selectedOption = this.getAttribute("data-option");
            checkRiddleAnswer(selectedOption);
        });
    });
    
    // 提示按钮事件
    const getHint = document.getElementById("get-hint");
    if (getHint) {
        getHint.addEventListener("click", showHint);
    }
}

// Create mechanism interface for the guardian hall
function createMechanismInterface(scene) {
    const interactiveElements = document.getElementById("interactive-elements");
    
    const mechanismHtml = `
        <div id="mechanism-container" class="bg-slate-700 p-3 rounded-md">
            <p class="text-amber-300 mb-2"><i class="fas fa-cogs mr-1"></i> <span id="mechanism-text">${scene.puzzleText}</span></p>
            
            <div id="lamp-options" class="grid grid-cols-2 gap-3 mb-4">
                ${scene.options.map((option, index) => `
                    <button class="lamp-option px-4 py-3 bg-slate-600 rounded-md hover:bg-slate-500 flex items-center" data-option="${option}">
                        <i class="fas fa-fire text-amber-400 mr-2"></i> ${option}
                    </button>
                `).join('')}
            </div>
            
            <div id="selected-lamps" class="flex flex-col gap-2 mb-4">
                <p class="text-sm text-gray-300">已选择的灯：</p>
                <div id="lamp-selection" class="flex gap-2 min-h-8 p-2 bg-slate-800 rounded-md">
                    <span class="text-gray-500 text-sm selected-lamps-placeholder">未选择</span>
                </div>
            </div>
            
            <div class="flex justify-center">
                <button id="submit-mechanism" class="btn-egypt px-4 py-2 rounded-md font-bold">熄灭选定的灯</button>
                <button id="reset-mechanism" class="ml-2 px-4 py-2 bg-slate-600 rounded-md hover:bg-slate-500">重置</button>
            </div>
            
            <p class="text-amber-100 text-sm mt-3 italic"><i class="fas fa-info-circle mr-1"></i> 提示：莎草纸上说"四灯灭三时"，你需要选择三盏灯熄灭。选择星座后点击"熄灭选定的灯"。</p>
        </div>
    `;
    
    interactiveElements.innerHTML = mechanismHtml;
    
    // 重置选择状态
    gameState.puzzleState.selectedLamps = [];
    
    // 添加机关事件监听器
    setupMechanismEvents();
}

// 设置第三关机关的事件监听
function setupMechanismEvents() {
    // 油灯选项事件
    const lampOptions = document.querySelectorAll(".lamp-option");
    lampOptions.forEach(option => {
        option.addEventListener("click", function() {
            const lampName = this.getAttribute("data-option");
            if (!gameState.puzzleState.selectedLamps.includes(lampName) && gameState.puzzleState.selectedLamps.length < 3) {
                gameState.puzzleState.selectedLamps.push(lampName);
                updateLampSelection();
            }
        });
    });
    
    // 提交按钮事件
    const submitMechanism = document.getElementById("submit-mechanism");
    if (submitMechanism) {
        submitMechanism.addEventListener("click", checkMechanismSolution);
    }
    
    // 重置按钮事件
    const resetMechanism = document.getElementById("reset-mechanism");
    if (resetMechanism) {
        resetMechanism.addEventListener("click", function() {
            gameState.puzzleState.selectedLamps = [];
            updateLampSelection();
        });
    }
}

// Create final puzzle interface
function createFinalPuzzleInterface(scene) {
    const interactiveElements = document.getElementById("interactive-elements");
    
    // 检查玩家是否拥有所需物品
    const hasAllRequiredItems = scene.requiredItems.every(item => 
        gameState.inventory.includes(item)
    );
    
    // 创建物品列表HTML，标记必需物品
    const createItemListHTML = () => {
        if (gameState.inventory.length === 0) {
            return '<span class="text-gray-500 text-sm">无可用物品</span>';
        }
        
        return gameState.inventory.map(item => {
            const isRequired = scene.requiredItems.includes(item);
            return `
                <div class="px-3 py-1 ${isRequired ? 'bg-amber-800' : 'bg-slate-700'} rounded text-amber-300 text-sm flex items-center">
                    <span>${item}</span>
                    ${isRequired ? '<i class="fas fa-check-circle text-green-400 ml-2"></i>' : ''}
                </div>
            `;
        }).join('');
    };
    
    const finalPuzzleHtml = `
        <div id="final-puzzle-container" class="bg-slate-700 p-3 rounded-md">
            <p class="text-amber-300 mb-2"><i class="fas fa-hat-wizard mr-1"></i> <span id="final-puzzle-text">${scene.puzzleText}</span></p>
            
            <div class="mb-4 p-3 bg-slate-800 rounded-md">
                <p class="text-sm text-gray-300 mb-2">你的物品：</p>
                <div id="item-list" class="flex flex-wrap gap-2">
                    ${createItemListHTML()}
                </div>
                ${!hasAllRequiredItems ? `
                <p class="text-red-400 text-sm mt-3">
                    <i class="fas fa-exclamation-triangle mr-1"></i> 
                    你缺少完成仪式所需的物品。请确保你已收集全部所需物品。
                </p>` : ''}
            </div>
            
            <div class="mb-4">
                <p class="text-sm text-gray-300 mb-2">解决方案：${hasAllRequiredItems ? '(提示：使用红宝石权杖)' : ''}</p>
                <input type="text" id="final-solution" class="w-full px-3 py-2 bg-slate-800 text-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-amber-500" placeholder="输入你的解决方案..." ${!hasAllRequiredItems ? 'disabled' : ''}>
            </div>
            
            <div class="flex justify-center">
                <button id="submit-final" class="btn-egypt px-4 py-2 rounded-md font-bold ${!hasAllRequiredItems ? 'opacity-50 cursor-not-allowed' : ''}">完成仪式</button>
            </div>
            
            <p class="text-amber-100 text-sm mt-3 italic"><i class="fas fa-info-circle mr-1"></i> 提示：${hasAllRequiredItems ? '描述如何使用收集到的物品完成仪式。例如："将红宝石权杖插入祭坛"' : '你需要收集更多物品，先完成前面的关卡。'}</p>
        </div>
    `;
    
    interactiveElements.innerHTML = finalPuzzleHtml;
    
    // 绑定最终谜题提交事件
    setupFinalPuzzleEvents();
}

// 设置第四关最终谜题的事件监听
function setupFinalPuzzleEvents() {
    const submitFinal = document.getElementById("submit-final");
    
    if (submitFinal) {
        // 判断是否有必要物品
        const currentScene = gameData.scenes[gameState.currentScene];
        const hasAllItems = currentScene.requiredItems.every(item => 
            gameState.inventory.includes(item)
        );
        
        // 如果缺少物品，显示提示并禁用按钮
        if (!hasAllItems) {
            submitFinal.classList.add('opacity-50', 'cursor-not-allowed');
            showFeedback("你缺少完成仪式的必要物品，请继续探索！", "warning");
        } else {
            submitFinal.classList.remove('opacity-50', 'cursor-not-allowed');
        }
        
        submitFinal.addEventListener("click", function() {
            if (hasAllItems) {
                checkFinalSolution();
            } else {
                showFeedback("你需要先收集所有必要的物品！", "warning");
            }
        });
    }
}

// Update lamp selection display
function updateLampSelection() {
    const lampSelection = document.getElementById("lamp-selection");
    const placeholder = document.querySelector(".selected-lamps-placeholder");
    
    if (gameState.puzzleState.selectedLamps.length > 0) {
        if (placeholder) placeholder.remove();
        
        // Clear and rebuild selection
        lampSelection.innerHTML = gameState.puzzleState.selectedLamps.map(lamp => `
            <div class="px-2 py-1 bg-slate-600 rounded text-amber-300 text-sm">
                ${lamp}
            </div>
        `).join('');
    } else {
        lampSelection.innerHTML = '<span class="text-gray-500 text-sm selected-lamps-placeholder">未选择</span>';
    }
}

// Update puzzle display
function updatePuzzleDisplay() {
    const solutionSlots = document.querySelectorAll(".solution-slot");
    
    // Clear all slots first
    solutionSlots.forEach(slot => {
        slot.textContent = "";
    });
    
    // Fill in selected symbols
    gameState.puzzleState.selectedSymbols.forEach((symbol, index) => {
        if (index < solutionSlots.length) {
            solutionSlots[index].textContent = symbol;
        }
    });
}

// Reset puzzle state
function resetPuzzleState() {
    gameState.puzzleState.selectedSymbols = [];
    updatePuzzleDisplay();
}

// Check puzzle solution
function checkPuzzleSolution() {
    const currentScene = gameData.scenes[gameState.currentScene];
    const solution = currentScene.solution;
    
    if (gameState.puzzleState.selectedSymbols.length !== solution.length) {
        showFeedback("请填入所有符号！", "warning");
        return;
    }
    
    const isCorrect = gameState.puzzleState.selectedSymbols.every((symbol, index) => {
        return symbol === solution[index];
    });
    
    if (isCorrect) {
        showFeedback(currentScene.feedback.success, "success");
        if (currentScene.item) {
            addItemToInventory(currentScene.item);
        }
        
        // Transition to next scene after delay
        setTimeout(() => {
            loadScene(currentScene.nextScene);
        }, 3000);
    } else {
        showFeedback(currentScene.feedback.fail, "error");
    }
}

// Check riddle answer
function checkRiddleAnswer(selectedOption) {
    const currentScene = gameData.scenes[gameState.currentScene];
    
    if (selectedOption === currentScene.answer) {
        showFeedback(currentScene.feedback.success, "success");
        
        // Transition to next scene after delay
        setTimeout(() => {
            loadScene(currentScene.nextScene);
        }, 3000);
    } else {
        showFeedback(currentScene.feedback.fail, "error");
    }
}

// Check mechanism solution
function checkMechanismSolution() {
    const currentScene = gameData.scenes[gameState.currentScene];
    const selectedLamps = gameState.puzzleState.selectedLamps;
    
    if (selectedLamps.length !== 3) {
        showFeedback("请选择三盏油灯！", "warning");
        return;
    }
    
    // Check if all selected lamps are in the solution and we have exactly the right lamps
    const isCorrect = selectedLamps.length === currentScene.solution.length && 
                     selectedLamps.every(lamp => currentScene.solution.includes(lamp)) &&
                     currentScene.solution.every(lamp => selectedLamps.includes(lamp));
    
    if (isCorrect) {
        showFeedback(currentScene.feedback.success, "success");
        if (currentScene.item) {
            addItemToInventory(currentScene.item);
        }
        
        // Transition to next scene after delay
        setTimeout(() => {
            loadScene(currentScene.nextScene);
        }, 3000);
    } else {
        showFeedback(currentScene.feedback.fail, "error");
    }
}

// Check final puzzle solution
function checkFinalSolution() {
    const currentScene = gameData.scenes[gameState.currentScene];
    const finalSolution = document.getElementById("final-solution").value.trim();
    
    // 检查玩家是否拥有所需物品
    const hasRequiredItems = currentScene.requiredItems.every(item => 
        gameState.inventory.includes(item)
    );
    
    if (!hasRequiredItems) {
        showFeedback("你缺少完成仪式的必要物品！请继续探索找到所有需要的物品。", "warning");
        return;
    }
    
    // 修改检查逻辑，使其更灵活，支持多种合理的答案表述
    const acceptableKeywords = ["红宝石权杖", "祭坛", "插入", "放入", "使用"];
    const keywordMatches = acceptableKeywords.filter(keyword => 
        finalSolution.includes(keyword)
    );
    
    // 只要包含"红宝石权杖"和"祭坛"中的任意一个，以及一个动作词，就视为正确
    const hasKeyItems = finalSolution.includes("红宝石权杖") || finalSolution.includes("祭坛");
    const hasAction = ["插入", "放入", "使用"].some(action => finalSolution.includes(action));
    
    if (keywordMatches.length >= 2 && (hasKeyItems && hasAction)) {
        showFeedback(currentScene.feedback.success, "success");
        
        // 游戏通关，显示成功信息
        setTimeout(() => {
            document.getElementById("interactive-elements").innerHTML = `
                <div class="bg-gradient-to-r from-amber-900 to-amber-700 p-6 rounded-md text-center">
                    <h3 class="text-amber-300 text-2xl mb-4">恭喜你完成了《法老王の诅咒》！</h3>
                    <p class="text-gray-200 mb-6">你成功破解了所有谜题，逃出了法老王的诅咒。</p>
                    <button id="play-again" class="btn-egypt px-6 py-3 rounded-md font-bold">再玩一次</button>
                </div>
            `;
            
            // 添加再玩一次按钮事件
            document.getElementById("play-again").addEventListener("click", function() {
                gameState.currentScene = "entrance";
                gameState.inventory = [];
                gameState.hintsRemaining = 2;
                gameState.puzzleState = {
                    selectedSymbols: [],
                    selectedLamps: []
                };
                loadScene("entrance");
            });
        }, 4000);
    } else if (finalSolution.length < 5) {
        showFeedback("请输入更详细的解决方案。", "warning");
    } else {
        showFeedback(currentScene.feedback.fail, "error");
    }
}

// Show hint
function showHint() {
    const currentScene = gameData.scenes[gameState.currentScene];
    
    if (gameState.hintsRemaining > 0) {
        const hintIndex = 2 - gameState.hintsRemaining;
        if (currentScene.hints && currentScene.hints[hintIndex]) {
            hintText.textContent = currentScene.hints[hintIndex];
            hintText.classList.remove("hidden");
            gameState.hintsRemaining--;
            hintsRemaining.textContent = gameState.hintsRemaining;
            
            if (gameState.hintsRemaining === 0) {
                getHint.classList.add("opacity-50", "pointer-events-none");
            }
        }
    }
}

// Show feedback message
function showFeedback(message, type) {
    feedbackMessage.textContent = message;
    feedbackMessage.classList.remove("hidden", "bg-green-700", "bg-red-700", "bg-yellow-700");
    
    switch(type) {
        case "success":
            feedbackMessage.classList.add("bg-green-700");
            break;
        case "error":
            feedbackMessage.classList.add("bg-red-700");
            break;
        case "warning":
            feedbackMessage.classList.add("bg-yellow-700");
            break;
    }
}

// Add item to inventory
function addItemToInventory(itemName) {
    // 防止重复添加同一物品
    if (!gameState.inventory.includes(itemName) && gameState.inventory.length < 4) {
        gameState.inventory.push(itemName);
        updateInventoryDisplay();
        
        // 显示物品获得提示
        const itemNotification = document.createElement('div');
        itemNotification.className = 'fixed bottom-10 right-10 bg-amber-800 text-amber-200 px-4 py-3 rounded shadow-lg flex items-center transition-opacity duration-500';
        itemNotification.innerHTML = `
            <i class="fas fa-gem mr-2"></i>
            <span>获得新物品：${itemName}</span>
        `;
        document.body.appendChild(itemNotification);
        
        // 3秒后隐藏物品提示
        setTimeout(() => {
            itemNotification.style.opacity = '0';
            setTimeout(() => itemNotification.remove(), 500);
        }, 3000);
        
        // 如果是最后一关所需的物品，发送提示
        const finalScene = gameData.scenes.final_chamber;
        if (finalScene.requiredItems.includes(itemName)) {
            const neededItems = finalScene.requiredItems.filter(item => !gameState.inventory.includes(item));
            if (neededItems.length > 0) {
                showFeedback(`你获得了重要物品：${itemName}！还需要寻找：${neededItems.join('、')}`, "success");
            } else {
                showFeedback(`你已收集齐所有需要的物品！前往最终密室完成仪式。`, "success");
            }
        }
    }
}

// Update inventory display
function updateInventoryDisplay() {
    const slots = document.querySelectorAll(".inventory-slot");
    
    slots.forEach((slot, index) => {
        if (index < gameState.inventory.length) {
            slot.innerHTML = `<span class="text-amber-300">${gameState.inventory[index]}</span>`;
        } else {
            slot.innerHTML = `<span class="text-gray-500 text-xs">空</span>`;
        }
    });
}

// 添加游戏调试功能（仅开发使用）
function debugGame() {
    console.log("游戏状态:", gameState);
    console.log("当前场景:", gameData.scenes[gameState.currentScene]);
    console.log("当前物品:", gameState.inventory);
    
    // 添加测试物品按钮
    const debugPanel = document.createElement('div');
    debugPanel.className = 'fixed top-4 right-4 bg-gray-800 p-2 rounded text-xs z-50';
    debugPanel.innerHTML = `
        <button id="debug-add-key" class="block mb-1 px-2 py-1 bg-blue-700 text-white rounded">添加青铜钥匙</button>
        <button id="debug-add-staff" class="block mb-1 px-2 py-1 bg-blue-700 text-white rounded">添加红宝石权杖</button>
        <button id="debug-goto-final" class="block px-2 py-1 bg-green-700 text-white rounded">跳到最终关</button>
    `;
    document.body.appendChild(debugPanel);
    
    document.getElementById('debug-add-key').addEventListener('click', () => {
        addItemToInventory('青铜钥匙');
    });
    
    document.getElementById('debug-add-staff').addEventListener('click', () => {
        addItemToInventory('红宝石权杖');
    });
    
    document.getElementById('debug-goto-final').addEventListener('click', () => {
        loadScene('final_chamber');
    });
}

// Initialize the game when page loads
document.addEventListener("DOMContentLoaded", initGame);